from django.shortcuts import render

from django import http
from django.views import View
from django.core.cache import cache

from csdp.utils.response_code import RETCODE
from .models import Area

# Create your views here.

class AreaView(View):
    def get(self, request):
        area_id = request.GET.get('area_id')
        if area_id is None:
            provinces_list = cache.get('provinces_list')
            if provinces_list is None:
                provinces_qs = Area.objects.filter(parent = None)
                provinces_list = []
                for provinces_model in provinces_qs:
                    provinces_list.append({
                        'id': provinces_model.id,
                        'name': provinces_model.name
                    })
                cache.set('provinces_list', provinces_list, 3600)
            return http.JsonResponse({'province_list': provinces_list, 'code': RETCODE.OK, 'errmsg': 'OK'})
        else:
            sub_data = cache.get('sub_data_%s' % area_id)
            if sub_data is None:
                try:
                    parent_model = Area.objects.get(id = area_id)
                    sub_qs = parent_model.subs.all()
                    sub_list = []
                    for sub_model in sub_qs:
                        sub_list.append({
                            'id': sub_model.id,
                            'name': sub_model.name
                        })
                    sub_data = {
                        'id': parent_model.id,
                        'name': parent_model.name,
                        'subs': sub_list
                    }
                    cache.set('sub_data_%s' % area_id, sub_data, 3600)
                except Area.DoesNotExist:
                    return http.HttpResponseForbidden('参数错误。')
            return http.JsonResponse({'code': RETCODE.OK, 'errmsg': 'OK', 'sub_data': sub_data})
